package loengud.w11;

/**
 * One thread increases a number,
 * the other thread checks
 * whether this number is divisible by 2.
 * Because we don't use locks, we get 
 * unexpected result: we increment value
 * always twice (after the next() method,
 * the value of i will be bigger by 2),
 * but when we check the value of i, in
 * some cases it does not divide by 2.
 * @author Ago
 *
 */
public class AlwaysEven {
	private int i = 0;
	/**
	 * Increases i by 2. It does it
	 * calling i++ two times. The problem is
	 * that getValue() might be called from 
	 * another thread (Thread "test")
	 * when i has been increased only once
	 * (e.g. number is not divisible by 2). 
	 */
	public void next() { i++; i++;}
	/**
	 * Returns the value of i.
	 * @return Value of i
	 */
	public int getValue() {return i;}
	
	public static void main(String[] args) {
		final AlwaysEven ae = new AlwaysEven();
		/*
		 * A "test" thread which
		 * checks if the getValue()
		 * method returns a number
		 * which is divisible by 2
		 */
		new Thread("test") {
			public void run() {
				while (true) {
					int val = ae.getValue();
					if (val % 2 != 0) {
						// doesn't divide by 2
						System.out.println(val);
						System.exit(0);
					}
				}
				
			};
		}.start(); // let's start this thread
		
		while(true) {
			// here we call the increment method
			// forever
			ae.next();
		}
	}
}
